#include "Socket.h"

Socket::Socket()
{
	m_Open=false;
	m_hasData = false;
}
Socket::Socket(TCPsocket tcp)
{
	m_TcpSock = tcp;
	m_Open=true;
	m_hasData = false;
	m_SockSet=SDLNet_AllocSocketSet(1);
	if(m_TcpSock)
	{
		SDLNet_TCP_AddSocket(m_SockSet,m_TcpSock);
	}
}
Socket::~Socket()
{
	if(m_TcpSock)
	{
//		SDLNet_TCP_Close(m_TcpSock);
//		SDLNet_FreeSocketSet(m_SockSet);
	}
}

std::string Socket::GetIp()
{
	std::string s;
	if(m_Ip.host == INADDR_NONE)
	{
		//failed
	}
	else
	{
		unsigned int i= m_Ip.host;
		unsigned int i4= (i&0xff000000)>>24;
		unsigned int i3= (i&0x00ff0000)>>16;
		unsigned int i2= (i&0x0000ff00)>>8;
		unsigned int i1= (i&0x000000ff);

		char buffer[20];
		sprintf(buffer,"%d.%d.%d.%d",i1,i2,i3,i4);

		s = buffer;
	}
	return s;
}

int Socket::GetPort()
{
	return m_Port;
}
void Socket::Close()
{
	m_Open=false;
	//SDLNet_FreeSocketSet(m_SockSet);
	//SDLNet_TCP_Close(m_TcpSock);
}

bool Socket::Send(SockMessage& sm)
{
	if(SDLNet_TCP_Send(m_TcpSock,sm.GetData(),sm.GetLength())!=sm.GetLength())
	{
		return false;
	}
	return true;
}

//Call HasData BEFORE Recv() to avoid block
bool Socket::Recv(SockMessage* sm)
{
	static const int MAXLEN = 2000;
	unsigned char msgrec[MAXLEN];

	do 
	{
		int numBytesReceived = SDLNet_TCP_Recv(m_TcpSock,msgrec,MAXLEN);
		if(numBytesReceived<=0)
		{
			//error
		}
		sm->m_Bytes.insert(sm->m_Bytes.end(),msgrec,msgrec + numBytesReceived);
		if(numBytesReceived <MAXLEN)
		{
			break;
		}
		m_hasData =false;
	} 
	while (HasData());
	return true;

}
bool Socket::HasData()
{
	if(m_hasData)
	{
		return true;
	}
	//poll socket
	int numReady=SDLNet_CheckSockets(m_SockSet,0);
	if(numReady>0)
	{
		if(SDLNet_SocketReady(m_TcpSock) != 1)
		{
			//error!
		}
		m_hasData = true;
	}
	return m_hasData;
}
bool Socket::IsOpen()
{
	return m_Open;
}